﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace B4Deal.Models
{
    public class UserManager
    {
        private B4Deal_DataEntities localDB;
        /*
                private const string MissingRole = "Role does not exist";
                private const string MissingUser = "User does not exist";
                private const string TooManyUser = "User already exists";
                private const string TooManyRole = "Role already exists";
                private const string AssignedRole = "Cannot delete a role with assigned users";*/

        public int NumberUser
        {
            get { return localDB.TAIKHOANs.Count(); }
        }

        public UserManager()
        {
            localDB = B4DealDatabase.b4Database;
        }

        public List<TAIKHOAN> GetAllUser()
        {
            List<TAIKHOAN> lst = (from user in localDB.TAIKHOANs
                                  orderby user.Email
                                  select user).ToList();

            return lst;
        }

        public TAIKHOAN GetUser(int mTK)
        {
            return localDB.TAIKHOANs.SingleOrDefault(user => user.MaTK == mTK);
        }

        public TAIKHOAN GetUser(string email)
        {
            return localDB.TAIKHOANs.SingleOrDefault(user => user.Email.Trim().CompareTo(email.Trim()) == 0);
        }

        public void CreateUser(string email, string name, string password)
        {
            if (string.IsNullOrEmpty(email.Trim()))
                throw new ArgumentException("Tài khoản không hợp lệ. Xin vui lòng kiểm tra lại thông tin.");
            if (string.IsNullOrEmpty(name.Trim()))
                throw new ArgumentException("Họ tên không hợp lệ. Xin vui lòng kiểm tra lại thông tin.");
            if (string.IsNullOrEmpty(password.Trim()))
                throw new ArgumentException("Mật khẩu không hợp lệ. Xin vui lòng kiểm tra lại thông tin.");
            if (this.localDB.TAIKHOANs.Any(user => user.Email.Trim().CompareTo(email.Trim()) == 0))
                throw new ArgumentException("Tài khoản đã tồn tại.");

            User newUser = new User()
            {
                Email = email,
                HoTen = name,
                Pass = password
                //Pass = FormsAuthentication.HashPasswordForStoringInConfigFile(password.Trim(), "md5"),
            };

            TAIKHOAN tk = new TAIKHOAN();
            Convert2TK(newUser, tk);
            try
            {
                localDB.AddToTAIKHOANs(tk);
            }
            catch (ArgumentException ae)
            {
                throw ae;
            }
            catch (Exception e)
            {
                throw new ArgumentException("Có lỗi xảy ra! Xin vui lòng kiểm tra và thử lại. " +
                    "Nếu vẫn còn lỗi xin liên hệ với admin.");
            }
        }

        private void Convert2TK(User u, TAIKHOAN tk)
        {
            tk.HoTen = u.HoTen;
            tk.Email = u.Email;
            tk.Password = u.Pass;
            tk.DienThoai = u.DienThoai;
            tk.TinhTrang = u.TinhTrang;
            tk.GioiTinh = u.GioiTinh;
            tk.LoaiTK = u.LoaiTK;
        }

        public bool DeleteUser(TAIKHOAN user)
        {
            if (!UserExists(user))
                throw new ArgumentException("User does not exist");

            TAIKHOAN u = GetUser(user.Email);
            u.TinhTrang = -1; //Delete User
            Save();
            return true;
        }

        public bool DeleteUser(string email)
        {
            return DeleteUser(GetUser(email));
        }

        public void Save()
        {
            localDB.SaveChanges();
        }

        public bool UserExists(TAIKHOAN user)
        {
            if (user == null)
                return false;

            return (localDB.TAIKHOANs.SingleOrDefault(u => u.MaTK == user.MaTK ||
                u.Email.Trim().CompareTo(user.Email.Trim()) == 0) != null);
        }

        public List<Order> GetOrdersByUser(TAIKHOAN user)
        {
            List<Order> orders = new List<Order>();
            using (var db = new B4Deal_DataEntities())
            {
                var temp = user.DONHANGs;
                foreach (var item in temp)
                {
                    var name = db.KHUYENMAIs.Where(x => x.MaKM == item.KhuyenMai).ToList().ElementAt(0).TenKM;
                    Order o = new Order(name, Convert.ToInt32(item.TinhTrang), Convert.ToDateTime(item.NgayDatHang), Convert.ToInt32(item.SoLuong));
                    o.MaDH = item.MaDH;
                    o.MaKM = item.KhuyenMai;
                    o.MaTK = item.TaiKhoan;
                    o.MaNH = item.NguoiNhan;
                    o.HinhThucThanhToan = (int)item.HinhThucThanhToan;
                    o.GhiChu = item.GhiChu;
                    o.PhiGiaoHang = item.PhiGiaoHang;
                    o.TinhTrangThanhToan = (int)item.TinhTrangThanhToan;
                    orders.Add(o);
                }
                return orders;
            }
        }

        public DOANHNGHIEP getBusiness(TAIKHOAN user)
        {
            return user.DOANHNGHIEPs.FirstOrDefault();
        }

        public bool checkBusiness(TAIKHOAN user)
        {
            if (user == null)
                return false;

            return (localDB.TAIKHOANs.SingleOrDefault(u => u.MaTK == user.MaTK &&
                u.DOANHNGHIEPs.Count > 0) != null);
        }

        public bool modifyBusiness(string user, string nameBUS, string levelBUS, string webBUS,
            string addrBUS, string typeBUS, string infoBUS)
        {
            if (user == null)
                return false;
            TAIKHOAN acc = localDB.TAIKHOANs.SingleOrDefault(u => u.Email.Trim().Equals(user) &&
                u.DOANHNGHIEPs.Count > 0);
            int maTK = (from ac in localDB.TAIKHOANs
                        where ac.Email.Equals(user)
                        select ac.MaTK).First();
            DOANHNGHIEP bsn = null;
            if (acc != null)
                bsn = acc.DOANHNGHIEPs.FirstOrDefault();
            try
            {
                if (bsn == null) //Don't have regis Business
                {
                    bsn = new DOANHNGHIEP();
                    bsn.TenDoanhNghiep = nameBUS;
                    bsn.ChucVu = levelBUS;
                    bsn.Website = webBUS;
                    bsn.DiaChi = addrBUS;
                    bsn.LoaiHinhKinhDoanh = typeBUS;
                    bsn.NoiMuonQuangCao = 0;
                    bsn.TaiKhoan = maTK;
                    bsn.TinhTrang = 0; //Haven't Pass by Admin
                    if (!String.IsNullOrEmpty(infoBUS))
                        bsn.ThongTinHopTac = infoBUS;
                    localDB.DOANHNGHIEPs.AddObject(bsn);
                }
                else
                {
                    bsn.TenDoanhNghiep = nameBUS;
                    bsn.ChucVu = levelBUS;
                    bsn.Website = webBUS;
                    bsn.DiaChi = addrBUS;
                    bsn.LoaiHinhKinhDoanh = typeBUS;
                    if (!String.IsNullOrEmpty(infoBUS))
                        bsn.ThongTinHopTac = infoBUS;
                }
                Save();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            return true;
        }
    }
}